<?php

/*
 * This file is part of the Dektrium project.
 *
 * (c) Dektrium project <http://github.com/dektrium/>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace app\models;

use Yii;
use yii\base\Model;

/**
 * Registration form collects user input on registration process, validates it and creates new User model.
 *
 * @author Dmitry Erofeev <dmeroff@gmail.com>
 */
class ChangePasswordForm extends Model
{
    public $oldPassword;

    public $password;

    public $confirmPassword;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['oldPassword', 'password', 'confirmPassword'], 'required'],
            ['confirmPassword', 'validateEqual'],
        ];
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validateEqual($attribute, $params)
    {
        if (!$this->hasErrors()) {
            if ($this->password != $this->confirmPassword) {
                $this->addError($attribute, '两次输入的密码不一致');
            }
        }
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'oldPassword' => '旧密码',
            'password' => '新密码',
            'confirmPassword' => '确认密码',
        ];
    }

    /**
     * @inheritdoc
     */
    public function formName()
    {
        return 'change-form';
    }

    /**
     * Registers a new user account. If registration was successful it will set flash message.
     *
     * @return bool
     */
    public function changePassword()
    {
        if (!$this->validate()) {
            return false;
        }
        $registerResult = \Yii::$app->util->postJson('/changePassWordAfterLogin', [
            'oldPassWord' => $this->oldPassword,
            'newPassWord' => $this->password,
            'sessionId' => \Yii::$app->loginState->getState('sessionId'),
            'userId' => \Yii::$app->loginState->getState('userId'),
        ]);
        if ($registerResult['returnCode'] == '200') {
            return true;
        } else {
            $this->addError('oldPassword', $registerResult['message']);
        }
    }

    /**
     * Loads attributes to the user model. You should override this method if you are going to add new fields to the
     * registration form. You can read more in special guide.
     *
     * By default this method set all attributes of this model to the attributes of User model, so you should properly
     * configure safe attributes of your User model.
     *
     * @param User $user
     */
    protected function loadAttributes(User $user)
    {
        $user->setAttributes($this->attributes);
    }
}